package com.ac.api.component.controller;

import com.base.annotation.Unsecured;
import com.ac.api.component.dao.CpArticleMapper;
import com.ac.api.component.dao.CpLabelMapper;
import com.ac.api.component.entity.CpText;
import com.ac.api.component.service.CpTextService;
import com.ac.api.component.vo.CpArticleVo;
import com.ac.api.component.vo.CpLabelVo;
import org.springframework.web.bind.annotation.RequestMapping;
import com.base.annotation.SysLog;
import org.springframework.web.bind.annotation.RestController;
import com.base.helper.BaseController;
import com.base.helper.Result;
import com.ac.api.component.entity.CpArticle;
import com.ac.api.component.service.CpArticleService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.validation.Valid;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gjj
 * @since 2024-10-26
 */
@Api(tags = "文章管理")
@RestController
@RequestMapping("/cpArticle")
public class CpArticleController extends BaseController {

        private static final Logger       LOG = LoggerFactory.getLogger(CpArticleController.class);
        @Autowired
        private              CpArticleService entityService;
        @Autowired
        private CpArticleMapper cpArticleMapper;
        @Autowired
        private CpTextService cpTextService;
        @Autowired
        private CpLabelMapper cpLabelMapper;

        @SysLog(action = "findByPage", value = "分页查询文章")
        @ApiOperation(value = "分页查询文章", notes = "分页查询文章")
        @RequestMapping(method = RequestMethod.GET)
        @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
                @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")})
        @Unsecured
        public Result<IPage<CpArticleVo>> findByPage(final CpArticleVo example, final Page page) {
            IPage<CpArticleVo>        records    = entityService.findByPage(example,page);
            return new Result(true, records);
        }

        @SysLog(action = "delete", value = "删除文章")
        @ApiOperation(value = "删除文章")
        @RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
        @ApiImplicitParam(name = "id", value = "文章ID", required = true, paramType = "path")
        public Result delete(@PathVariable final Integer id) {
            try {
                CpArticle cpArticle=entityService.getById(id);
                cpArticle.setState("f");
                entityService.updateById(cpArticle);
                return new Result(true, "成功删除文章", null);
            } catch (DataIntegrityViolationException e) {
                LOG.error("删除文章失败", e);
                return new Result(false, "删除文章失败", "该文章不能删除，存在其他关联数据");
            } catch (Exception e) {
                LOG.error("删除文章失败", e);
                return new Result(false, "删除文章失败", e.getMessage());
            }
        }

        @SysLog(action = "one", value = "查询单个文章")
        @ApiOperation(value = "查询单个文章")
        @RequestMapping(value = "{id}", method = {RequestMethod.GET})
        @ApiImplicitParam(name = "id", value = "文章ID", required = true, paramType = "path")
        @Unsecured
        public Result one(@PathVariable final Integer id) {
            try {
                CpArticle entity = cpArticleMapper.getArticleById(id);
                if (entity == null) {
                    return new Result(false, new CpArticle());
                }
                //增加浏览数
                entityService.lambdaUpdate()
                        .set(CpArticle::getView,entity.getView()+1)
                        .eq(CpArticle::getId,id)
                        .update();
                return new Result(true, entity);
            } catch (Exception e) {
                LOG.error("查询单个文章失败", e);
                return new Result(false, new CpArticle());
            }
        }

        @SysLog(action = "add", value = "添加文章")
        @ApiOperation(value = "添加文章")
        @RequestMapping(method = {RequestMethod.POST})
        public Result add(@Valid @RequestBody final CpArticleVo cpArticleVo, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "保存文章失败", errorMsg, map);
                } else {
                    CpLabelVo cpLabelVo=cpLabelMapper.findByName(cpArticleVo.getModuleName(),cpArticleVo.getLabelName());
                    if (cpLabelVo == null) {
                        return new Result(false, "","无法找到对应模块和标签");
                    }
                    //新增文章
                    cpArticleVo.setView(0);
                    cpArticleVo.setCreatetime(new Date());
                    cpArticleVo.setState("t");
                    cpArticleVo.setCplabelid(cpLabelVo.getLabelId());
                    entityService.save(cpArticleVo);
                    //新增内容
                    CpText cpText=new CpText();
                    cpText.setText(cpArticleVo.getText());
                    cpTextService.save(cpText);
                    //回填文章id
                    cpArticleVo.setTextid(cpText.getId());
                    entityService.updateById(cpArticleVo);
                    return new Result(true, "成功保存文章", null);
                }
            } catch (Exception e) {
                LOG.error("添加文章失败", e);
                return new Result(false, "保存文章失败", e.getMessage());
            }
        }

        @SysLog(action = "update", value = "修改文章")
        @ApiOperation(value = "修改文章")
        @RequestMapping(method = {RequestMethod.PUT})
        public Result update(@Valid @RequestBody final CpArticleVo entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "修改文章失败", errorMsg, map);
                } else {
                    if (null == entity.getId()) {
                         throw new RuntimeException("id不能为空");
                    }
                    //查找对应模块名称和标签名称的标签
                    CpLabelVo cpLabelVo=cpLabelMapper.findByName(entity.getModuleName(),entity.getLabelName());
                    entity.setCplabelid(cpLabelVo.getLabelId());
                    entityService.updateById(entity);
                    //更新文章内容
                    CpArticle cpArticle=entityService.getById(entity.getId());
                    cpTextService.lambdaUpdate().set(CpText::getText,entity.getText()).eq(CpText::getId,cpArticle.getTextid()).update();
                    return new Result(true, "成功修改文章", null);
                }
            } catch (Exception e) {
                LOG.error("修改文章失败", e);
                return new Result(false, "修改文章失败", e.getMessage());
            }
        }

        @ApiOperation(value = "全部文章")
        @RequestMapping(value = "all", method = RequestMethod.GET)
        public Result<List<CpArticle>> all(CpArticle example) {
            List<CpArticle> entitys = entityService.list(example);
            if (null != entitys) {
                return new Result<>(true, entitys);
            }
            return new Result<>(true, Collections.emptyList());
        }

}

